package com.dji.sample.wayline.controller;

import com.dji.sample.common.model.CustomClaim;
import com.dji.sample.common.model.ResponseResult;
import com.dji.sample.manage.service.DevicePlayLineInfoService;
import com.dji.sample.wayline.service.FlightPlanInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

import static com.dji.sample.component.AuthInterceptor.TOKEN_CLAIM;

/**
 * @author yjt
 * @date 2023-03-24
 * @description:
 */
@RestController
@RequestMapping("/flight")
public class FlightPlanInfoController {

    @Autowired
    FlightPlanInfoService flightPlanInfoService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @Autowired
    DevicePlayLineInfoService devicePlayLineInfoService;

    private static final String FLIGHT_PLAY_KEY = "flight:device:";
    public static final String DEVICE_PLAY_LINE_KEY="device:plan:line:";

    @GetMapping("list")
    public ResponseResult<?> queryList(@RequestParam String account) {
        return ResponseResult.success(flightPlanInfoService.queryList(account));
    }

    @PostMapping("start")
    public ResponseResult<?> start(@RequestParam Long planId, @RequestParam String deviceSn, HttpServletRequest request) {
        CustomClaim customClaim = (CustomClaim)request.getAttribute(TOKEN_CLAIM);
        stringRedisTemplate.opsForValue().set(FLIGHT_PLAY_KEY + deviceSn, planId.toString(), 2, TimeUnit.HOURS);
        //更新到flightPlanInfo
        String id = stringRedisTemplate.opsForValue().get(DEVICE_PLAY_LINE_KEY+deviceSn);
        if(StringUtils.hasText(id)){
            devicePlayLineInfoService.updatePlanId(Long.valueOf(id),planId.toString(),customClaim.getUsername());
        }
        return ResponseResult.success();
    }

    @PostMapping("end")
    public ResponseResult<?> end(@RequestParam String deviceSn) {
        stringRedisTemplate.delete(FLIGHT_PLAY_KEY + deviceSn);
        return ResponseResult.success();
    }

    @GetMapping("plan")
    public ResponseResult<?> getLastPlan(@RequestParam String deviceSn) {
        String val = stringRedisTemplate.opsForValue().get(FLIGHT_PLAY_KEY + deviceSn);
        if (val == null) {
            return ResponseResult.error("未查寻到任务");
        }
        return ResponseResult.success(flightPlanInfoService.queryById(Long.valueOf(val)));
    }
}
